#!/usr/bin/env python
# coding=utf-8
# @FileName :yaml_util.py
# @Time     :2022/2/10 9:04
# @Author   :ZXC
# @Desc     :YAML文件读取类
import json
from pathlib import Path

import yaml
from loguru import logger
from yaml.scanner import ScannerError
from string import Template


class YamlUtil(object):
    @staticmethod
    def read_yaml(file_path=None) -> dict:
        """
        读取yaml文件
        Args:
            file_path: yaml文件路径

        Returns:

        """

        # 没传文件路径或文件路径不存在时,抛出异常
        if not file_path or not Path(file_path).exists() or Path(file_path).suffix != '.yaml':
            raise FileNotFoundError(f"yaml文件【{file_path}】不存在,读取失败")

        logger.debug(f'正在读取yaml文件【{file_path}】')
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                value = yaml.load(f.read(), Loader=yaml.FullLoader)
                logger.debug(f'yaml文件【{file_path}】读取完成')
                return value
        except FileNotFoundError:
            raise FileNotFoundError(f"yaml文件【{file_path}】不存在,读取失败")
        except ScannerError:
            raise ScannerError(f"yaml文件【{file_path}】数据不正确，读取失败,请检查文件数据格式")
        except Exception as e:
            raise Exception(f"yaml文件读取失败{e}")

    @staticmethod
    def write_yaml(file_path, data):
        """
        写入数据到yaml文件
        Args:
            data: 写入的数据
            file_path: yaml文件路径

        Returns:

        """
        logger.debug(f'正在写入数据到yaml文件【{file_path}】')
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                yaml.dump(data, f)
                logger.debug(f'yaml文件{file_path}写入完成')
        except FileNotFoundError:
            raise FileNotFoundError(f"yaml文件【{file_path}】不存在,写入失败")
        except Exception as e:
            raise Exception(f"写入数据到yaml文件失败{e}")

    @staticmethod
    def read_and_replace(data_pool: dict, file_path=None):
        """
        读取yaml数据，并替换与数据池匹配的数据
        匹配格式为${var_name}
        Args:
            data_pool: 数据池，字典格式
            file_path: yaml文件路径

        Returns:

        """
        yaml_data = YamlUtil.read_yaml(file_path)
        logger.debug(f'正在解析替换yaml文件【{file_path}】的数据,数据池为：{data_pool}')
        try:
            yaml_data_str = json.dumps(yaml_data)
            new_data_str = Template(yaml_data_str).safe_substitute(data_pool)
            value = yaml.safe_load(new_data_str)
            logger.debug(f'解析替换yaml文件【{file_path}】的数据完成')
            return value
        except Exception as e:
            raise Exception(f"替换与数据池匹配的数据时出错{e}")


if __name__ == '__main__':
    from config.settings import DATA_DIR

    #
    filepath = DATA_DIR.joinpath('获取机构树.yaml')
    # cases = YamlUtil.read_yaml(filepath)
    # print(cases[0].values())
    # print(cases)
    # print(json.dumps(cases, ensure_ascii=False))

    excel_data_generator = YamlUtil.read_yaml(filepath)

    print(excel_data_generator)
